import os
import time
import tkinter as tk

import imagehash
import pyautogui
from PIL import Image, ImageTk
import cv2
import aircv as ac
from exceptiongroup import catch

from ai_util import AiUtil
from draw_util import DrawUtil
from screen_util import ScreenUtil
import config
import ui_kit
from wechat import *


# 鼠标左键按下事件
def left_mouse_down(event):
    global left_mouse_down_x, left_mouse_down_y
    # 记录按下的坐标，赋值给全局变量
    left_mouse_down_x = event.x
    left_mouse_down_y = event.y

# 鼠标左键按下并移动
def moving_mouse(event):
    global sole_rectangle # 绘制的矩形
    # 鼠标按下的x,y
    global left_mouse_down_x, left_mouse_down_y
    moving_mouse_x = event.x
    moving_mouse_y = event.y
    # 如果原来画过矩形，删除前一个矩形，绘制出新的
    if sole_rectangle is not None:
        canvas.delete(sole_rectangle)
    sole_rectangle = canvas.create_rectangle(left_mouse_down_x, left_mouse_down_y, moving_mouse_x,moving_mouse_y, outline='red')

# 鼠标左键抬起事件
def left_mouse_up(event):
    global clip_img_path

    # 记录抬起时的坐标，鼠标左键抬起时x,y坐标
    left_mouse_up_x = event.x
    left_mouse_up_y = event.y
    # 通过抬起的点减去按下的点，比划矩形，计算出宽和高
    width = left_mouse_up_x - left_mouse_down_x
    height = left_mouse_up_y - left_mouse_down_y
    # 如果宽高太小，有可能是点击了一下，或者想放弃这次操作
    if width < 20 or height < 20:
        print("size is to small")
        return
    # 保存文件
    corp_image = image.crop((left_mouse_down_x, left_mouse_down_y, left_mouse_up_x, left_mouse_up_y))
    rgb_image = corp_image.convert("RGB")
    rgb_image.save(clip_img_path)

def ocr():
    pass

def test_aircv():
    source_image = ac.imread(config.source_image_path)
    template_image = ac.imread(config.search_image_path)

    match_result = ac.find_sift(source_image, template_image)
    print(f"match_result = {match_result}")

def show_image(image):
    cv2.imshow("Detected", image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

def open_wechat():
    match_result = AiUtil.find_sift(config.screenshot_save_path, config.wechat_image_path)
    print(f"match_result = {match_result}")
    center = match_result["center"]
    # test_point(source_image_path, center)
    os.system(f"adb shell input tap {center[0]} {center[1]}")


# Press the green button in the gutter to run the script.
if __name__ == '__main__':

    my_log.install_logger()

    wechat_path = ""
    Wechat.instance().install(wechat_path)
    Wechat.batch_send_message(["陈健", "李东益"], "测试批量发送")
    exit()
    # screenshot()
    # open_wechat()
    # test()我是自动化工具发出的消息，用于测试

    # test_aircv()

    # is_click = ui_kit.click_image(config.wechat_contact_image_path)
    # is_click = ui_kit.click_text("李东益")
    # if is_click:
    #     ui_kit.write("我是自动化工具发出的消息，用于测试")

    Wechat.setup_position()
    positions = Wechat.instance().positions
    print(f"positions = {positions}")
    # exit()

    is_contact_open = None
    try:
        point = pyautogui.locateCenterOnScreen(image=config.wechat_contact_open_image_path)
        # print(f"point_o = {point}")
        is_contact_open = True
    except:
        pass

    try:
        point = pyautogui.locateCenterOnScreen(image=config.wechat_contact_close_image_path)
        # print(f"point_c = {point}")
        pyautogui.click(point[0], point[1])
        is_contact_open = False
    except:
        pass

    if is_contact_open is None:
        print(f"is_contact_open is None")
        exit()

    print(f"is_contact_open = {is_contact_open}")

    for i in range(10):
        pyautogui.scroll(-5)
        # time.sleep(0.1)
        is_click = ui_kit.click_text("陈健")
        if is_click:
            print(f"is_click is is_click")
            break
            # ui_kit.write("我是自动化工具发出的消息，用于测试")



    exit()

    path = config.res_dir + 'source.png'
    search_text = "批批网"
    result = AiUtil.find_text(path, search_text)
    if result is None:
        print(f"find_text=[{search_text}] result Not Found")
    else:
        print(f"find_text=[{search_text}] result = {result}")
        points = result[0]
        center = DrawUtil.cal_center(points)

        source_image = cv2.imread(path)
        DrawUtil.draw_point(source_image, center)
        DrawUtil.draw_rectangle(source_image, points)
        show_image(source_image)

    print("===== exit =====")
    exit()

    # 鼠标左键按下时x, y坐标
    left_mouse_down_x, left_mouse_down_y = 0, 0
    sole_rectangle = None  # 画出的矩形
    target = f"{CACHE_DIR}{os.sep}img"
    w_flag = True
    clip_img_path = "cache/clip_img.jpg"

    while w_flag:
        window = tk.Tk()
        window.title("手机截屏转文字")
        frame = tk.Frame()
        frame.pack()

        button = tk.Button(frame, text="截屏", command=ScreenUtil.mobile_screenshot)
        button.pack(side="left", padx=10, pady=8)

        button = tk.Button(frame, text="识别", command=ocr)
        button.pack(side="left", padx=10, pady=8)

        button = tk.Button(frame, text="退出", command=exit)
        button.pack(side="left", padx=50, pady=8)

        image = Image.open(img_path)
        image_x, image_y = image.size
        img = ImageTk.PhotoImage(image)

        canvas = tk.Canvas(window, width=image_x, height=image_y, bg='white')
        # 画布建立完成后，左上角是坐标（0, 0），向右x轴递增，向下y轴递增。
        canvas.create_image(0, 0, anchor='nw', image=img)

        canvas.pack()

        canvas.bind('<Button-1>', left_mouse_down)  # 鼠标左键按下
        canvas.bind('<ButtonRelease-1>', left_mouse_up)  # 鼠标左键释放
        # canvas.bind('<Button-3>', right_mouse_down)  # 鼠标右键按下
        # canvas.bind('<ButtonRelease-3>', right_mouse_up)  # 鼠标右键释放
        canvas.bind('<B1-Motion>', moving_mouse)  # 鼠标左键按下并移动

        window.mainloop()

